<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>简易计量系统 - 审核管理端 (腾讯云版)</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/qrcodejs/1.0.0/qrcode.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js"></script>
    <!-- 引入腾讯云 CloudBase SDK -->
    <!-- <script src="https://cdn.jsdelivr.net/npm/@cloudbase/js-sdk@2.17.15/database/dist/index.esm.min.js"></script> -->
    <script src="https://static.cloudbase.net/cloudbase-js-sdk/2.17.3/cloudbase.full.js"></script>
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&family=Noto+Sans+SC:wght@400;500;700&display=swap" rel="stylesheet">
    <style>
        body { font-family: 'Inter', 'Noto Sans SC', sans-serif; }
        .sidebar-link { @apply block w-full text-left px-4 py-3 text-lg rounded-lg transition-colors duration-200; }
        .sidebar-link.active { @apply bg-blue-600 text-white font-semibold shadow-md; }
        .sidebar-link:not(.active) { @apply text-gray-600 dark:text-gray-300 hover:bg-gray-200 dark:hover:bg-gray-700; }
        
        .modal-backdrop {
            @apply fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50;
            @apply transition-opacity duration-300 ease-in-out;
            @apply opacity-0 pointer-events-none;
        }
        .modal-backdrop.is-open {
            @apply opacity-100 pointer-events-auto;
        }
        .modal-content {
            @apply bg-white dark:bg-gray-800 p-8 rounded-xl shadow-2xl w-full max-w-lg;
            @apply transition-all duration-300 ease-in-out;
            transform: scale(0.95);
            max-height: 90vh; overflow-y: auto;
        }
        .modal-backdrop.is-open .modal-content {
            transform: scale(1);
        }

        .page { display: none; }
        .page.active { display: block; }
        .loader { @apply w-12 h-12 border-4 border-blue-500 border-t-transparent rounded-full animate-spin; }
    </style>
</head>
<body class="bg-gray-100 dark:bg-gray-900 text-gray-800 dark:text-gray-200">
    <div id="loading-overlay" class="fixed inset-0 bg-white dark:bg-gray-900 z-[100] flex flex-col items-center justify-center">
        <div class="loader"></div>
        <p id="loading-text" class="mt-4 text-lg font-semibold">正在连接数据库...</p>
    </div>
    <div class="flex h-screen">
        <aside class="w-64 bg-white dark:bg-gray-800 p-4 flex flex-col shadow-lg">
            <h1 class="text-2xl font-bold text-blue-600 dark:text-blue-400 mb-8 text-center">管理后台</h1>
            <nav id="sidebar-nav" class="flex flex-col space-y-2">
                <button data-page="dashboard" class="sidebar-link active">审核面板</button>
                <button data-page="records" class="sidebar-link">记录与报表</button>
                <button data-page="users" class="sidebar-link">用户管理</button>
                <button data-page="models" class="sidebar-link">型号管理</button>
                <button data-page="salary" class="sidebar-link">工资结算</button>
            </nav>
            <div class="mt-auto text-center text-xs text-gray-400"><p>简易计量系统 v2.0 (Tencent Cloud)</p></div>
        </aside>
        <main class="flex-1 p-8 overflow-y-auto">
             <!-- 所有页面HTML结构保持不变 -->
            <div id="page-dashboard" class="page active">
                <h2 class="text-3xl font-bold mb-6">待审核记录</h2>
                <div class="bg-white dark:bg-gray-800 p-6 rounded-xl shadow-md"><div class="overflow-x-auto"><table class="w-full text-left"><thead><tr class="border-b dark:border-gray-700"><th class="p-4">用户</th><th class="p-4">型号</th><th class="p-4">工序</th><th class="p-4">数量</th><th class="p-4">提交时间</th><th class="p-4 text-center">操作</th></tr></thead><tbody id="pending-records-table"></tbody></table></div></div>
            </div>
            <div id="page-records" class="page"><h2 class="text-3xl font-bold mb-6">记录查询与报表</h2><div class="bg-white dark:bg-gray-800 p-6 rounded-xl shadow-md mb-6"><div class="grid grid-cols-1 md:grid-cols-2 gap-4"><div><label class="font-semibold">日期筛选:</label><div class="flex flex-wrap items-center gap-2 mt-2"><button id="filter-today" class="bg-sky-500 hover:bg-sky-600 text-white font-bold py-2 px-4 rounded-lg">今日</button><button id="filter-this-month" class="bg-sky-500 hover:bg-sky-600 text-white font-bold py-2 px-4 rounded-lg">本月</button><input type="date" id="filter-start-date" class="p-2 border rounded-lg dark:bg-gray-700 dark:border-gray-600"><span>至</span><input type="date" id="filter-end-date" class="p-2 border rounded-lg dark:bg-gray-700 dark:border-gray-600"></div></div><div><label class="font-semibold">字段筛选:</label><div class="flex flex-wrap items-center gap-2 mt-2"><select id="filter-user" class="p-2 border rounded-lg dark:bg-gray-700 dark:border-gray-600"></select><select id="filter-model" class="p-2 border rounded-lg dark:bg-gray-700 dark:border-gray-600"></select><select id="filter-process" class="p-2 border rounded-lg dark:bg-gray-700 dark:border-gray-600"></select><select id="filter-color" class="p-2 border rounded-lg dark:bg-gray-700 dark:border-gray-600"></select><select id="filter-size" class="p-2 border rounded-lg dark:bg-gray-700 dark:border-gray-600"></select></div></div></div><div class="mt-4 flex justify-end gap-4"><button id="filter-apply" class="bg-blue-600 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded-lg">应用筛选</button><button id="filter-reset" class="bg-gray-500 hover:bg-gray-600 text-white font-bold py-2 px-4 rounded-lg">重置</button></div></div>
                <div id="report-view" class="bg-white dark:bg-gray-800 p-6 rounded-xl shadow-md mb-6 hidden">
                    <h3 class="text-2xl font-bold mb-4">报表分析</h3>
                    <div class="grid md:grid-cols-3 gap-6">
                        <div class="md:col-span-1 p-4 bg-gray-50 dark:bg-gray-700 rounded-lg">
                            <h4 class="text-lg font-semibold mb-2">数据总览</h4>
                            <p class="text-3xl font-bold text-blue-500" id="report-total-quantity"></p>
                            <p class="text-gray-500 dark:text-gray-400">总计件数</p>
                            <p class="text-3xl font-bold text-green-500 mt-4" id="report-total-price"></p>
                            <p class="text-gray-500 dark:text-gray-400">预估总工价</p>
                        </div>
                        <div class="md:col-span-2 relative h-80">
                            <canvas id="report-chart"></canvas>
                        </div>
                    </div>
                </div>
                <div class="bg-white dark:bg-gray-800 p-6 rounded-xl shadow-md">
                    <div class="flex justify-between items-center mb-4">
                        <h3 class="text-2xl font-bold">记录明细</h3>
                        <button id="generate-image-btn" class="bg-teal-600 hover:bg-teal-700 text-white font-bold py-2 px-4 rounded-lg">生成报表图片</button>
                    </div>
                    <div class="overflow-x-auto"><table class="w-full text-left"><thead><tr class="border-b dark:border-gray-700"><th class="p-4 w-12"><input type="checkbox" id="select-all-checkbox"></th><th class="p-4">用户</th><th class="p-4">型号/工序</th><th class="p-4">颜色/码数</th><th class="p-4">数量</th><th class="p-4">审核时间</th><th class="p-4">状态</th></tr></thead><tbody id="all-records-table"></tbody></table></div>
                </div>
            </div>
            <div id="page-users" class="page"><div class="flex justify-between items-center mb-6"><h2 class="text-3xl font-bold">用户管理</h2><button id="add-user-btn" class="bg-blue-600 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded-lg">添加新用户</button></div><div class="bg-white dark:bg-gray-800 p-6 rounded-xl shadow-md"><table class="w-full text-left"><thead><tr class="border-b dark:border-gray-700"><th class="p-4">用户ID</th><th class="p-4">姓名</th><th class="p-4 text-center">操作</th></tr></thead><tbody id="users-table"></tbody></table></div></div>
            <div id="page-models" class="page"><div class="flex justify-between items-center mb-6"><h2 class="text-3xl font-bold">型号与工价管理</h2><button id="add-model-btn" class="bg-blue-600 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded-lg">添加新型号</button></div><div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6" id="models-list"></div></div>
            <div id="page-salary" class="page">
                <div class="bg-white dark:bg-gray-800 p-6 rounded-xl shadow-md">
                    <h2 class="text-3xl font-bold mb-6 border-b pb-4">对员工结算</h2>
                    <div class="flex space-x-4 mb-4">
                        <select id="salary-user-filter" class="p-2 border rounded-lg dark:bg-gray-700 dark:border-gray-600"></select>
                        <input type="month" id="salary-month-filter" class="p-2 border rounded-lg dark:bg-gray-700 dark:border-gray-600">
                        <button id="calculate-salary-btn" class="bg-green-600 hover:bg-green-700 text-white font-bold py-2 px-4 rounded-lg">生成结算</button>
                    </div>
                    <div id="salary-report"></div>
                </div>
                <div class="bg-white dark:bg-gray-800 p-6 rounded-xl shadow-md mt-8">
                    <h2 class="text-3xl font-bold mb-6 border-b pb-4">对供货方结算</h2>
                     <div class="flex space-x-4 mb-4">
                        <input type="month" id="supplier-salary-month-filter" class="p-2 border rounded-lg dark:bg-gray-700 dark:border-gray-600">
                        <button id="calculate-supplier-salary-btn" class="bg-purple-600 hover:bg-purple-700 text-white font-bold py-2 px-4 rounded-lg">生成结算</button>
                    </div>
                    <div id="supplier-salary-report"></div>
                </div>
            </div>
        </main>
    </div>
    <div id="qr-modal" class="modal-backdrop hidden"><div class="modal-content"><h3 class="text-2xl font-bold mb-4 text-center">用户登录二维码</h3><p class="mb-2 text-center">请用户使用微信扫描</p><div id="qrcode-container" class="flex justify-center p-4 bg-white rounded-lg"></div><p id="qr-user-name" class="mt-4 text-lg font-semibold text-center"></p><button id="close-qr-modal" class="mt-6 w-full bg-gray-300 hover:bg-gray-400 dark:bg-gray-600 dark:hover:bg-gray-500 font-bold py-2 px-6 rounded-lg">关闭</button></div></div>
    <div id="model-modal" class="modal-backdrop hidden"><div class="modal-content"><h3 id="model-modal-title" class="text-2xl font-bold mb-6">添加新型号</h3><form id="model-form" class="space-y-4"><input type="hidden" id="model-id-input"><div class="grid grid-cols-2 gap-4"><div><label for="model-name" class="block text-sm font-medium text-gray-700 dark:text-gray-300">型号名称</label><input type="text" id="model-name" required class="mt-1 block w-full px-3 py-2 bg-white dark:bg-gray-700 border border-gray-300 dark:border-gray-600 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500"></div><div><label for="model-settlement-price" class="block text-sm font-medium text-gray-700 dark:text-gray-300">结算单价 (对供货方)</label><input type="number" id="model-settlement-price" step="0.01" required class="mt-1 block w-full px-3 py-2 bg-white dark:bg-gray-700 border border-gray-300 dark:border-gray-600 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500"></div></div><div><label for="model-colors" class="block text-sm font-medium text-gray-700 dark:text-gray-300">可选颜色 (用逗号分隔)</label><input type="text" id="model-colors" required class="mt-1 block w-full px-3 py-2 bg-white dark:bg-gray-700 border border-gray-300 dark:border-gray-600 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500"></div><div><label for="model-sizes" class="block text-sm font-medium text-gray-700 dark:text-gray-300">可选码数 (用逗号分隔)</label><input type="text" id="model-sizes" required class="mt-1 block w-full px-3 py-2 bg-white dark:bg-gray-700 border border-gray-300 dark:border-gray-600 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500"></div><hr class="dark:border-gray-600"><h4 class="text-lg font-semibold">工序与工价 (对员工)</h4><div id="model-processes-container" class="space-y-2"></div><button type="button" id="add-process-row" class="text-sm bg-gray-200 dark:bg-gray-600 hover:bg-gray-300 dark:hover:bg-gray-500 py-1 px-3 rounded-md">添加工序</button><div class="flex justify-end space-x-4 pt-4"><button type="button" id="cancel-model-form" class="bg-gray-300 hover:bg-gray-400 dark:bg-gray-600 dark:hover:bg-gray-500 font-bold py-2 px-6 rounded-lg">取消</button><button type="submit" class="bg-blue-600 hover:bg-blue-700 text-white font-bold py-2 px-6 rounded-lg">保存</button></div></form></div></div>
    <div id="record-edit-modal" class="modal-backdrop hidden"><div class="modal-content"><h3 class="text-2xl font-bold mb-6">编辑待审核记录</h3><form id="record-edit-form" class="space-y-4"><input type="hidden" id="record-id-input"><div><label for="record-model-select" class="block text-sm font-medium text-gray-700 dark:text-gray-300">型号</label><select id="record-model-select" required class="mt-1 block w-full px-3 py-2 bg-white dark:bg-gray-700 border border-gray-300 dark:border-gray-600 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500"></select></div><div><label for="record-color-select" class="block text-sm font-medium text-gray-700 dark:text-gray-300">颜色</label><select id="record-color-select" required class="mt-1 block w-full px-3 py-2 bg-white dark:bg-gray-700 border border-gray-300 dark:border-gray-600 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500"></select></div><div><label for="record-size-select" class="block text-sm font-medium text-gray-700 dark:text-gray-300">码数</label><select id="record-size-select" required class="mt-1 block w-full px-3 py-2 bg-white dark:bg-gray-700 border border-gray-300 dark:border-gray-600 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500"></select></div><div><label for="record-process-select" class="block text-sm font-medium text-gray-700 dark:text-gray-300">工序</label><select id="record-process-select" required class="mt-1 block w-full px-3 py-2 bg-white dark:bg-gray-700 border border-gray-300 dark:border-gray-600 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500"></select></div><div><label for="record-quantity-input" class="block text-sm font-medium text-gray-700 dark:text-gray-300">数量</label><input type="number" id="record-quantity-input" required class="mt-1 block w-full px-3 py-2 bg-white dark:bg-gray-700 border border-gray-300 dark:border-gray-600 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500"></div><div class="flex justify-end space-x-4 pt-4"><button type="button" id="cancel-record-edit-form" class="bg-gray-300 hover:bg-gray-400 dark:bg-gray-600 dark:hover:bg-gray-500 font-bold py-2 px-6 rounded-lg">取消</button><button type="submit" class="bg-blue-600 hover:bg-blue-700 text-white font-bold py-2 px-6 rounded-lg">保存更改</button></div></form></div></div>
    <div id="user-modal" class="modal-backdrop hidden"><div class="modal-content"><h3 class="text-2xl font-bold mb-6">添加新用户</h3><form id="user-form" class="space-y-4"><div><label for="user-name-input" class="block text-sm font-medium text-gray-700 dark:text-gray-300">用户姓名</label><input type="text" id="user-name-input" required class="mt-1 block w-full px-3 py-2 bg-white dark:bg-gray-700 border border-gray-300 dark:border-gray-600 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500"></div><div class="flex justify-end space-x-4 pt-4"><button type="button" id="cancel-user-form" class="bg-gray-300 hover:bg-gray-400 dark:bg-gray-600 dark:hover:bg-gray-500 font-bold py-2 px-6 rounded-lg">取消</button><button type="submit" class="bg-blue-600 hover:bg-blue-700 text-white font-bold py-2 px-6 rounded-lg">保存用户</button></div></form></div></div>
    <!-- Hidden container for generating the image -->
    <div id="image-export-container" class="fixed -left-[9999px] p-8 bg-white"></div>

    <script>
    window.onload = () => {
        if (typeof cloudbase === 'undefined') {
            document.getElementById('loading-text').innerHTML = '<p class="text-red-500">腾讯云SDK加载失败，请检查网络或浏览器设置。</p>';
            document.querySelector('#loading-overlay .loader').style.display = 'none';
            return;
        }

        const app = cloudbase.init({
            env: "cloud1-0g8v1tvz2ddf6e59" // <--- 在这里粘贴您的腾讯云环境ID
        });
        const db = app.database();
        const _ = db.command;

        const loadingOverlay = document.getElementById('loading-overlay');
        const loadingText = document.getElementById('loading-text');

        let allUsers = [], allModels = [], allRecords = [], reportChartInstance = null;
        
        const pages = document.querySelectorAll('.page');
        const navLinks = document.querySelectorAll('.sidebar-link');
        const pendingRecordsTable = document.getElementById('pending-records-table');
        const allRecordsTable = document.getElementById('all-records-table');
        const usersTable = document.getElementById('users-table');
        const modelsList = document.getElementById('models-list');
        const addUserBtn = document.getElementById('add-user-btn');
        const qrModal = document.getElementById('qr-modal');
        const closeQrModalBtn = document.getElementById('close-qr-modal');
        const qrcodeContainer = document.getElementById('qrcode-container');
        const qrUserName = document.getElementById('qr-user-name');
        const salaryUserFilter = document.getElementById('salary-user-filter');
        const salaryMonthFilter = document.getElementById('salary-month-filter');
        const calculateSalaryBtn = document.getElementById('calculate-salary-btn');
        const salaryReport = document.getElementById('salary-report');
        const reportView = document.getElementById('report-view');
        const reportTotalQuantity = document.getElementById('report-total-quantity');
        const reportTotalPrice = document.getElementById('report-total-price');
        const reportChartCanvas = document.getElementById('report-chart');
        const addModelBtn = document.getElementById('add-model-btn');
        const modelModal = document.getElementById('model-modal');
        const modelModalTitle = document.getElementById('model-modal-title');
        const modelForm = document.getElementById('model-form');
        const cancelModelFormBtn = document.getElementById('cancel-model-form');
        const modelIdInput = document.getElementById('model-id-input');
        const modelNameInput = document.getElementById('model-name');
        const modelSettlementPriceInput = document.getElementById('model-settlement-price');
        const modelColorsInput = document.getElementById('model-colors');
        const modelSizesInput = document.getElementById('model-sizes');
        const modelProcessesContainer = document.getElementById('model-processes-container');
        const addProcessRowBtn = document.getElementById('add-process-row');
        const recordEditModal = document.getElementById('record-edit-modal');
        const recordEditForm = document.getElementById('record-edit-form');
        const cancelRecordEditFormBtn = document.getElementById('cancel-record-edit-form');
        const recordIdInput = document.getElementById('record-id-input');
        const recordModelSelect = document.getElementById('record-model-select');
        const recordColorSelect = document.getElementById('record-color-select');
        const recordSizeSelect = document.getElementById('record-size-select');
        const recordProcessSelect = document.getElementById('record-process-select');
        const recordQuantityInput = document.getElementById('record-quantity-input');
        const userModal = document.getElementById('user-modal');
        const userForm = document.getElementById('user-form');
        const cancelUserFormBtn = document.getElementById('cancel-user-form');
        const userNameInput = document.getElementById('user-name-input');
        
        const filterUserSelect = document.getElementById('filter-user');
        const filterModelSelect = document.getElementById('filter-model');
        const filterProcessSelect = document.getElementById('filter-process');
        const filterColorSelect = document.getElementById('filter-color');
        const filterSizeSelect = document.getElementById('filter-size');
        const filterApplyBtn = document.getElementById('filter-apply');
        const filterResetBtn = document.getElementById('filter-reset');
        const filterStartDate = document.getElementById('filter-start-date');
        const filterEndDate = document.getElementById('filter-end-date');
        const filterTodayBtn = document.getElementById('filter-today');
        const filterMonthBtn = document.getElementById('filter-this-month');
        const selectAllCheckbox = document.getElementById('select-all-checkbox');
        const generateImageBtn = document.getElementById('generate-image-btn');
        
        const supplierSalaryMonthFilter = document.getElementById('supplier-salary-month-filter');
        const calculateSupplierSalaryBtn = document.getElementById('calculate-supplier-salary-btn');
        const supplierSalaryReport = document.getElementById('supplier-salary-report');

        navLinks.forEach(link => {
            link.addEventListener('click', () => {
                const pageId = link.dataset.page;
                navLinks.forEach(nav => nav.classList.remove('active'));
                link.classList.add('active');
                pages.forEach(page => page.classList.toggle('active', page.id === `page-${pageId}`));
                if (pageId === 'records') initRecordsPage();
                if (pageId === 'salary') initSalaryPage();
            });
        });

        const formatDateTime = (date) => {
            if (!date) return '-';
            const d = new Date(date);
            return isNaN(d.getTime()) ? '-' : d.toLocaleString('zh-CN');
        };
        const formatDate = (date) => date ? new Date(date).toLocaleDateString('zh-CN') : 'N/A';

        function renderPendingRecords(records) {
            pendingRecordsTable.innerHTML = '';
            if (records.length === 0) {
                pendingRecordsTable.innerHTML = `<tr><td colspan="6" class="p-4 text-center text-gray-500">没有待审核的记录</td></tr>`;
                return;
            }
            records.forEach(rec => {
                const user = allUsers.find(u => u._id === rec.userId);
                pendingRecordsTable.innerHTML += `<tr class="border-b dark:border-gray-700 hover:bg-gray-50 dark:hover:bg-gray-700/50"><td class="p-4">${user ? user.name : '未知用户'}</td><td class="p-4">${rec.model}</td><td class="p-4">${rec.process}</td><td class="p-4 font-semibold">${rec.quantity}</td><td class="p-4">${formatDateTime(rec.submitTime)}</td><td class="p-4 text-center space-x-2"><button data-id="${rec._id}" class="edit-record-btn bg-yellow-500 hover:bg-yellow-600 text-white px-3 py-1 rounded">编辑</button><button data-id="${rec._id}" class="approve-btn bg-green-500 hover:bg-green-600 text-white px-3 py-1 rounded">批准</button><button data-id="${rec._id}" class="reject-btn bg-red-500 hover:bg-red-600 text-white px-3 py-1 rounded">拒绝</button></td></tr>`;
            });
        }

        function renderFilteredRecords(filteredRecords) {
            allRecordsTable.innerHTML = '';
            selectAllCheckbox.checked = false;
            if (!filteredRecords || filteredRecords.length === 0) {
                allRecordsTable.innerHTML = `<tr><td colspan="7" class="p-4 text-center text-gray-500">没有符合条件的记录</td></tr>`;
                reportView.classList.add('hidden');
                return;
            }
            filteredRecords.forEach(rec => {
                const user = allUsers.find(u => u._id === rec.userId);
                allRecordsTable.innerHTML += `<tr class="border-b dark:border-gray-700">
                    <td class="p-4"><input type="checkbox" class="record-checkbox" data-id="${rec._id}"></td>
                    <td class="p-4">${user ? user.name : '未知用户'}</td>
                    <td class="p-4">${rec.model} / ${rec.process}</td>
                    <td class="p-4">${rec.color} / ${rec.size}</td>
                    <td class="p-4 font-semibold">${rec.quantity}</td>
                    <td class="p-4">${formatDateTime(rec.reviewTime)}</td>
                    <td class="p-4"><span class="bg-green-200 text-green-800 text-xs font-semibold mr-2 px-2.5 py-0.5 rounded-full dark:bg-green-900 dark:text-green-300">已批准</span></td>
                </tr>`;
            });
            renderReport(filteredRecords);
        }

        const doughnutTextPlugin = {
            id: 'doughnutText',
            afterDraw(chart) {
                if (chart.config.type !== 'doughnut') return;
                const { ctx, chartArea: { top, width, height } } = chart;
                const total = chart.getDatasetMeta(0).total;
                ctx.save();
                ctx.font = 'bold 24px Inter, sans-serif';
                ctx.fillStyle = document.body.classList.contains('dark') ? '#e5e7eb' : '#1f2937';
                ctx.textAlign = 'center';
                ctx.textBaseline = 'middle';
                ctx.fillText(total.toLocaleString(), width / 2, height / 2 + top - 10);
                ctx.font = '16px Inter, sans-serif';
                ctx.fillStyle = '#6b7280';
                ctx.fillText('总计件数', width / 2, height / 2 + top + 20);
                ctx.restore();
            }
        };

        function renderReport(records) {
            let totalQuantity = 0, totalPrice = 0;
            const modelData = {};
            records.forEach(rec => {
                const model = allModels.find(m => m.name === rec.model);
                let processPrice = 0;
                if (model && model.processes) {
                    const process = model.processes.find(p => p.name === rec.process);
                    if (process) processPrice = process.price;
                }
                totalQuantity += rec.quantity;
                totalPrice += rec.quantity * processPrice;
                modelData[rec.model] = (modelData[rec.model] || 0) + rec.quantity;
            });
            reportTotalQuantity.textContent = totalQuantity.toLocaleString();
            reportTotalPrice.textContent = `¥ ${totalPrice.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`;
            if (reportChartInstance) reportChartInstance.destroy();
            
            reportChartInstance = new Chart(reportChartCanvas, {
                type: 'doughnut',
                data: {
                    labels: Object.keys(modelData),
                    datasets: [{
                        label: '件数',
                        data: Object.values(modelData),
                        backgroundColor: ['#4f46e5', '#7c3aed', '#db2777', '#f97316', '#0ea5e9', '#10b981', '#eab308', '#64748b'],
                        borderColor: document.body.classList.contains('dark') ? '#1f2937' : '#fff',
                        borderWidth: 4,
                        hoverOffset: 8
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    cutout: '70%',
                    plugins: {
                        legend: {
                            position: 'right',
                            labels: { padding: 20, boxWidth: 12, font: { size: 14 } }
                        },
                        title: { display: true, text: '各型号产量占比', font: { size: 18 }, padding: { bottom: 20 } },
                        tooltip: {
                            callbacks: {
                                label: function(context) {
                                    const label = context.label || '';
                                    const value = context.raw || 0;
                                    const total = context.chart.getDatasetMeta(0).total;
                                    const percentage = total > 0 ? ((value / total) * 100).toFixed(1) + '%' : '0%';
                                    return `${label}: ${value} 件 (${percentage})`;
                                }
                            }
                        }
                    }
                },
                plugins: [doughnutTextPlugin]
            });
            reportView.classList.remove('hidden');
        }

        function renderUsers() {
            usersTable.innerHTML = '';
            allUsers.forEach(user => {
                usersTable.innerHTML += `<tr class="border-b dark:border-gray-700"><td class="p-4">${user._id}</td><td class="p-4 font-semibold">${user.name}</td><td class="p-4 text-center"><button data-id="${user._id}" class="qr-btn bg-blue-500 hover:bg-blue-600 text-white px-3 py-1 rounded">生成二维码</button></td></tr>`;
            });
        }
        
        function renderModels() {
            modelsList.innerHTML = '';
            allModels.forEach(model => {
                const processesHtml = model.processes.map(p => `<p><strong>工序:</strong> ${p.name}, <strong>工价:</strong> ¥ ${p.price.toFixed(2)}</p>`).join('');
                modelsList.innerHTML += `<div class="p-6 border rounded-xl dark:border-gray-700 bg-white dark:bg-gray-800 shadow-sm flex flex-col"><h4 class="text-xl font-bold">${model.name}</h4><div class="mt-4 space-y-2 text-gray-600 dark:text-gray-300 flex-grow"><p class="font-semibold text-red-500"><strong>结算单价:</strong> ¥ ${model.settlementPrice.toFixed(2)}</p><hr class="my-2 dark:border-gray-600"><p><strong>可选颜色:</strong> ${model.colors.join(', ')}</p><p><strong>可选码数:</strong> ${model.sizes.join(', ')}</p><hr class="my-2 dark:border-gray-600">${processesHtml}</div><div class="mt-6 pt-4 border-t dark:border-gray-600 flex justify-end space-x-2"><button data-id="${model._id}" class="edit-model-btn bg-yellow-500 hover:bg-yellow-600 text-white font-bold py-1 px-3 rounded-md text-sm">编辑</button><button data-id="${model._id}" class="delete-model-btn bg-red-600 hover:bg-red-700 text-white font-bold py-1 px-3 rounded-md text-sm">删除</button></div></div>`;
            });
        }

        function initSalaryPage() {
            salaryUserFilter.innerHTML = `<option value="all">所有用户</option>`;
            allUsers.forEach(u => salaryUserFilter.innerHTML += `<option value="${u._id}">${u.name}</option>`);
            const currentMonth = new Date().toISOString().slice(0, 7);
            salaryMonthFilter.value = currentMonth;
            supplierSalaryMonthFilter.value = currentMonth;
            salaryReport.innerHTML = '';
            supplierSalaryReport.innerHTML = '';
        }

        function initRecordsPage() {
            filterStartDate.value = '';
            filterEndDate.value = '';
            filterUserSelect.value = 'all';
            filterModelSelect.value = 'all';
            filterProcessSelect.value = 'all';
            filterColorSelect.value = 'all';
            filterSizeSelect.value = 'all';
            applyAllFilters();
        }

        function showModal(modalElement) {
            modalElement.classList.remove('hidden');
            setTimeout(() => {
                modalElement.classList.add('is-open');
            }, 10);
        }

        function hideModal(modalElement) {
            modalElement.classList.remove('is-open');
            setTimeout(() => {
                modalElement.classList.add('hidden');
            }, 300);
        }

        document.body.addEventListener('click', async (e) => {
            const target = e.target.closest('button');
            if (!target) return;
            const id = target.dataset.id;
            if (target.matches('.approve-btn, .reject-btn')) {
                const status = target.matches('.approve-btn') ? 'approved' : 'rejected';
                await db.collection('records').doc(id).update({ status, reviewTime: new Date() });
            } else if (target.matches('.qr-btn')) {
                const user = allUsers.find(u => u._id === id);
                if (user) {
                    qrcodeContainer.innerHTML = '';
                    const userAppUrl = `./user.html?userId=${user._id}`;
                    new QRCode(qrcodeContainer, { text: userAppUrl, width: 200, height: 200 });
                    qrUserName.textContent = `用户: ${user.name}`;
                    showModal(qrModal);
                }
            } else if (target.matches('.edit-record-btn')) {
                showRecordEditModal(id);
            }
        });

        addUserBtn.addEventListener('click', () => showModal(userModal));
        cancelUserFormBtn.addEventListener('click', () => hideModal(userModal));
        userForm.addEventListener('submit', async (e) => {
            e.preventDefault();
            const name = userNameInput.value;
            if (name && name.trim()) {
                await db.collection('users').add({ name: name.trim() });
                hideModal(userModal);
                userForm.reset();
            }
        });
        
        closeQrModalBtn.addEventListener('click', () => hideModal(qrModal));

        calculateSalaryBtn.addEventListener('click', () => {
            const selectedUserId = salaryUserFilter.value;
            const [year, month] = salaryMonthFilter.value.split('-').map(Number);
            const recordsToCalculate = allRecords.filter(r => {
                if (r.status !== 'approved' || !r.reviewTime) return false;
                const recordDate = new Date(r.reviewTime);
                return recordDate.getFullYear() === year && (recordDate.getMonth() + 1) === month && (selectedUserId === 'all' || r.userId === selectedUserId);
            });
            let reportHtml = `<h3 class="text-2xl font-bold mb-4">对员工工资结算报告 (${year}年${month}月)</h3>`;
            if (recordsToCalculate.length === 0) { salaryReport.innerHTML = reportHtml + `<p>该时段内没有已结算的记录。</p>`; return; }
            const userSalaries = {};
            recordsToCalculate.forEach(rec => {
                const model = allModels.find(m => m.name === rec.model);
                let processPrice = 0;
                if (model && model.processes) {
                    const process = model.processes.find(p => p.name === rec.process);
                    if (process) processPrice = process.price;
                }
                const salary = processPrice * rec.quantity;
                if (!userSalaries[rec.userId]) userSalaries[rec.userId] = { total: 0, records: [] };
                userSalaries[rec.userId].total += salary;
                userSalaries[rec.userId].records.push({ ...rec, salary });
            });
            reportHtml += '<div class="space-y-6">';
            for(const userId in userSalaries) {
                const user = allUsers.find(u => u._id === userId);
                const userData = userSalaries[userId];
                const processBreakdown = userData.records.map(r => {
                    const model = allModels.find(m => m.name === r.model);
                    let processPrice = 0;
                    if (model && model.processes) {
                        const process = model.processes.find(p => p.name === r.process);
                        if (process) processPrice = process.price;
                    }
                    return `<tr><td class="p-2">${r.model}/${r.process}</td><td class="p-2 text-right">${r.quantity}</td><td class="p-2 text-right">¥ ${processPrice.toFixed(2)}</td><td class="p-2 text-right font-semibold">¥ ${r.salary.toFixed(2)}</td></tr>`;
                }).join('');
                reportHtml += `<div class="p-4 border rounded-lg dark:border-gray-600"><div class="flex justify-between items-center mb-2"><h4 class="text-xl font-semibold">用户: ${user.name}</h4><p class="text-2xl font-bold text-green-500">总计: ¥ ${userData.total.toFixed(2)}</p></div><table class="w-full text-sm"><thead><tr class="border-b dark:border-gray-700"><th class="p-2 text-left">型号/工序</th><th class="p-2 text-right">数量</th><th class="p-2 text-right">单价</th><th class="p-2 text-right">小计</th></tr></thead><tbody>${processBreakdown}</tbody></table></div>`;
            }
            reportHtml += '</div>';
            salaryReport.innerHTML = reportHtml;
        });

        calculateSupplierSalaryBtn.addEventListener('click', () => {
            const [year, month] = supplierSalaryMonthFilter.value.split('-').map(Number);
            const recordsToCalculate = allRecords.filter(r => {
                if (r.status !== 'approved' || !r.reviewTime) return false;
                const recordDate = new Date(r.reviewTime);
                return recordDate.getFullYear() === year && (recordDate.getMonth() + 1) === month;
            });

            let reportHtml = `<h3 class="text-2xl font-bold mb-4">对供货方结算报告 (${year}年${month}月)</h3>`;
            const completedQuantities = {};

            recordsToCalculate.forEach(rec => {
                const model = allModels.find(m => m.name === rec.model);
                if (!model || !model.processes || model.processes.length === 0) return;
                
                const lastProcess = model.processes[model.processes.length - 1].name;
                if (rec.process === lastProcess) {
                    if (!completedQuantities[rec.model]) {
                        completedQuantities[rec.model] = 0;
                    }
                    completedQuantities[rec.model] += rec.quantity;
                }
            });

            if (Object.keys(completedQuantities).length === 0) {
                supplierSalaryReport.innerHTML = reportHtml + `<p>该时段内没有完成最终工序的记录。</p>`;
                return;
            }

            let grandTotal = 0;
            let tableRowsHtml = '';
            for (const modelName in completedQuantities) {
                const model = allModels.find(m => m.name === modelName);
                if (model) {
                    const quantity = completedQuantities[modelName];
                    const settlementPrice = model.settlementPrice;
                    const totalAmount = quantity * settlementPrice;
                    grandTotal += totalAmount;
                    tableRowsHtml += `
                        <tr class="border-b dark:border-gray-700">
                            <td class="p-3">${modelName}</td>
                            <td class="p-3 text-right">${quantity.toLocaleString()}</td>
                            <td class="p-3 text-right">¥ ${settlementPrice.toFixed(2)}</td>
                            <td class="p-3 text-right font-semibold">¥ ${totalAmount.toFixed(2)}</td>
                        </tr>
                    `;
                }
            }

            reportHtml += `
                <table class="w-full text-left">
                    <thead>
                        <tr class="border-b-2 dark:border-gray-600">
                            <th class="p-3">型号</th>
                            <th class="p-3 text-right">完成数量</th>
                            <th class="p-3 text-right">结算单价</th>
                            <th class="p-3 text-right">总金额</th>
                        </tr>
                    </thead>
                    <tbody>${tableRowsHtml}</tbody>
                    <tfoot>
                        <tr class="border-t-2 dark:border-gray-600 font-bold">
                            <td class="p-3" colspan="3">总结算金额</td>
                            <td class="p-3 text-right text-xl text-red-500">¥ ${grandTotal.toFixed(2)}</td>
                        </tr>
                    </tfoot>
                </table>
            `;
            supplierSalaryReport.innerHTML = reportHtml;
        });
        
        function addProcessRow(process = { name: '', price: 0 }) {
            const row = document.createElement('div');
            row.className = 'flex items-center gap-2 process-row';
            row.innerHTML = `
                <input type="text" placeholder="工序名称" value="${process.name}" class="process-name-input mt-1 block w-full px-3 py-2 bg-white dark:bg-gray-700 border border-gray-300 dark:border-gray-600 rounded-md shadow-sm" required>
                <input type="number" step="0.01" placeholder="工价" value="${process.price.toFixed(2)}" class="process-price-input mt-1 block w-full px-3 py-2 bg-white dark:bg-gray-700 border border-gray-300 dark:border-gray-600 rounded-md shadow-sm" required>
                <button type="button" class="remove-process-row bg-red-500 text-white rounded-full w-6 h-6 flex items-center justify-center">&times;</button>
            `;
            row.querySelector('.remove-process-row').addEventListener('click', () => row.remove());
            modelProcessesContainer.appendChild(row);
        }

        function showModelModal(model = null) {
            modelForm.reset();
            modelProcessesContainer.innerHTML = '';
            if (model) {
                modelModalTitle.textContent = '编辑型号';
                modelIdInput.value = model._id;
                modelNameInput.value = model.name;
                modelSettlementPriceInput.value = model.settlementPrice ? model.settlementPrice.toFixed(2) : '0.00';
                modelColorsInput.value = model.colors.join(', ');
                modelSizesInput.value = model.sizes.join(', ');
                model.processes.forEach(p => addProcessRow(p));
            } else {
                modelModalTitle.textContent = '添加新型号';
                modelIdInput.value = '';
                addProcessRow();
            }
            showModal(modelModal);
        }
        addModelBtn.addEventListener('click', () => showModelModal());
        addProcessRowBtn.addEventListener('click', () => addProcessRow());
        cancelModelFormBtn.addEventListener('click', () => hideModal(modelModal));
        modelForm.addEventListener('submit', async (e) => {
            e.preventDefault();
            const id = modelIdInput.value;
            const processes = [];
            document.querySelectorAll('.process-row').forEach(row => {
                const name = row.querySelector('.process-name-input').value;
                const price = parseFloat(row.querySelector('.process-price-input').value);
                if (name && !isNaN(price)) {
                    processes.push({ name, price });
                }
            });
            const modelData = {
                name: modelNameInput.value,
                settlementPrice: parseFloat(modelSettlementPriceInput.value),
                colors: modelColorsInput.value.split(',').map(s => s.trim()).filter(Boolean),
                sizes: modelSizesInput.value.split(',').map(s => s.trim()).filter(Boolean),
                processes: processes
            };
            if (id) {
                await db.collection('models').doc(id).update(modelData);
            } else {
                await db.collection('models').add(modelData);
            }
            hideModal(modelModal);
        });
        modelsList.addEventListener('click', async (e) => {
            const target = e.target.closest('button');
            if (!target) return;
            const id = target.dataset.id;
            if (target.matches('.edit-model-btn')) {
                const model = allModels.find(m => m._id === id);
                if (model) showModelModal(model);
            } else if (target.matches('.delete-model-btn')) {
                if (confirm('确定要删除这个型号吗？')) {
                    await db.collection('models').doc(id).remove();
                }
            }
        });
        
        function populateSelect(selectElement, options, selectedValue) {
            selectElement.innerHTML = '';
            options.forEach(option => {
                const opt = document.createElement('option');
                opt.value = option;
                opt.textContent = option;
                if (option === selectedValue) opt.selected = true;
                selectElement.appendChild(opt);
            });
        }
        function showRecordEditModal(recordId) {
            const record = allRecords.find(r => r._id === recordId);
            if (!record) return;
            recordIdInput.value = record._id;
            recordQuantityInput.value = record.quantity;
            populateSelect(recordModelSelect, allModels.map(m => m.name), record.model);
            function updateDependentDropdowns(modelName) {
                const selectedModel = allModels.find(m => m.name === modelName);
                if (selectedModel) {
                    populateSelect(recordColorSelect, selectedModel.colors, record.color);
                    populateSelect(recordSizeSelect, selectedModel.sizes, record.size);
                    populateSelect(recordProcessSelect, selectedModel.processes.map(p => p.name), record.process);
                }
            }
            updateDependentDropdowns(record.model);
            recordModelSelect.onchange = () => {
                const newModelName = recordModelSelect.value;
                const newSelectedModel = allModels.find(m => m.name === newModelName);
                if (newSelectedModel) {
                    populateSelect(recordColorSelect, newSelectedModel.colors, newSelectedModel.colors[0]);
                    populateSelect(recordSizeSelect, newSelectedModel.sizes, newSelectedModel.sizes[0]);
                    populateSelect(recordProcessSelect, newSelectedModel.processes.map(p => p.name), newSelectedModel.processes[0].name);
                }
            };
            showModal(recordEditModal);
        }
        cancelRecordEditFormBtn.addEventListener('click', () => hideModal(recordEditModal));
        recordEditForm.addEventListener('submit', async (e) => {
            e.preventDefault();
            const recordId = recordIdInput.value;
            await db.collection('records').doc(recordId).update({
                model: recordModelSelect.value,
                color: recordColorSelect.value,
                size: recordSizeSelect.value,
                process: recordProcessSelect.value,
                quantity: parseInt(recordQuantityInput.value)
            });
            hideModal(recordEditModal);
        });

        function populateDetailFilters() {
            filterUserSelect.innerHTML = '<option value="all">所有用户</option>';
            allUsers.forEach(u => filterUserSelect.innerHTML += `<option value="${u._id}">${u.name}</option>`);

            filterModelSelect.innerHTML = '<option value="all">所有型号</option>';
            allModels.forEach(m => filterModelSelect.innerHTML += `<option value="${m.name}">${m.name}</option>`);

            const allProcesses = [...new Set(allModels.flatMap(m => m.processes.map(p => p.name)))];
            filterProcessSelect.innerHTML = '<option value="all">所有工序</option>';
            allProcesses.forEach(p => filterProcessSelect.innerHTML += `<option value="${p}">${p}</option>`);

            const allColors = [...new Set(allModels.flatMap(m => m.colors))];
            filterColorSelect.innerHTML = '<option value="all">所有颜色</option>';
            allColors.forEach(c => filterColorSelect.innerHTML += `<option value="${c}">${c}</option>`);

            const allSizes = [...new Set(allModels.flatMap(m => m.sizes))];
            filterSizeSelect.innerHTML = '<option value="all">所有尺码</option>';
            allSizes.forEach(s => filterSizeSelect.innerHTML += `<option value="${s}">${s}</option>`);
        }

        function applyAllFilters() {
            const userId = filterUserSelect.value;
            const model = filterModelSelect.value;
            const process = filterProcessSelect.value;
            const color = filterColorSelect.value;
            const size = filterSizeSelect.value;
            const startDate = filterStartDate.value ? new Date(filterStartDate.value) : null;
            const endDate = filterEndDate.value ? new Date(filterEndDate.value) : null;

            if(startDate) startDate.setHours(0, 0, 0, 0);
            if(endDate) endDate.setHours(23, 59, 59, 999);

            let filtered = allRecords.filter(r => r.status === 'approved');

            if (startDate && endDate) {
                filtered = filtered.filter(r => {
                    const reviewDate = new Date(r.reviewTime);
                    return reviewDate >= startDate && reviewDate <= endDate;
                });
            }
            if (userId !== 'all') {
                filtered = filtered.filter(r => r.userId === userId);
            }
            if (model !== 'all') {
                filtered = filtered.filter(r => r.model === model);
            }
            if (process !== 'all') {
                filtered = filtered.filter(r => r.process === process);
            }
            if (color !== 'all') {
                filtered = filtered.filter(r => r.color === color);
            }
            if (size !== 'all') {
                filtered = filtered.filter(r => r.size === size);
            }
            
            renderFilteredRecords(filtered);
        }

        filterApplyBtn.addEventListener('click', applyAllFilters);
        filterResetBtn.addEventListener('click', initRecordsPage);
        filterTodayBtn.addEventListener('click', () => {
            const today = new Date();
            const dateString = today.toISOString().split('T')[0];
            filterStartDate.value = dateString;
            filterEndDate.value = dateString;
            applyAllFilters();
        });
        filterMonthBtn.addEventListener('click', () => {
            const today = new Date();
            const startOfMonth = new Date(today.getFullYear(), today.getMonth(), 1).toISOString().split('T')[0];
            const endOfMonth = new Date(today.getFullYear(), today.getMonth() + 1, 0).toISOString().split('T')[0];
            filterStartDate.value = startOfMonth;
            filterEndDate.value = endOfMonth;
            applyAllFilters();
        });
        
        selectAllCheckbox.addEventListener('change', (e) => {
            document.querySelectorAll('.record-checkbox').forEach(checkbox => {
                checkbox.checked = e.target.checked;
            });
        });
        
        generateImageBtn.addEventListener('click', () => {
            const selectedIds = [...document.querySelectorAll('.record-checkbox:checked')].map(cb => cb.dataset.id);
            if (selectedIds.length === 0) {
                alert('请至少选择一条记录来生成报表。');
                return;
            }

            const selectedRecords = allRecords.filter(r => selectedIds.includes(r._id));
            let totalQuantity = 0;
            
            const tableRows = selectedRecords.map(rec => {
                totalQuantity += rec.quantity;
                return `
                    <tr style="border-bottom: 1px solid #e2e8f0;">
                        <td style="padding: 8px;">${formatDate(rec.reviewTime)}</td>
                        <td style="padding: 8px;">${rec.model}</td>
                        <td style="padding: 8px; text-align: right;">${rec.quantity}</td>
                    </tr>
                `;
            }).join('');

            const reportHtml = `
                <div style="width: 600px; font-family: sans-serif; color: #1a202c;">
                    <h2 style="text-align: center; font-size: 24px; margin-bottom: 24px;">完成记录报表</h2>
                    <table style="width: 100%; border-collapse: collapse;">
                        <thead>
                            <tr style="background-color: #edf2f7; border-bottom: 2px solid #cbd5e0;">
                                <th style="padding: 12px; text-align: left;">日期</th>
                                <th style="padding: 12px; text-align: left;">型号</th>
                                <th style="padding: 12px; text-align: right;">数量</th>
                            </tr>
                        </thead>
                        <tbody>
                            ${tableRows}
                        </tbody>
                    </table>
                    <div style="text-align: right; font-size: 18px; font-weight: bold; margin-top: 24px; padding-top: 12px; border-top: 2px solid #1a202c;">
                        总计数量: ${totalQuantity}
                    </div>
                </div>
            `;

            const exportContainer = document.getElementById('image-export-container');
            exportContainer.innerHTML = reportHtml;
            
            html2canvas(exportContainer).then(canvas => {
                const link = document.createElement('a');
                link.download = '完成记录报表.png';
                link.href = canvas.toDataURL('image/png');
                link.click();
                exportContainer.innerHTML = '';
            });
        });


        async function main() {
            try {
                loadingText.textContent = "正在进行身份验证...";
                const auth = app.auth();
                const loginState = await auth.getLoginState();
                if (!loginState) {
                    await auth.signInAnonymously();
                }

                loadingText.textContent = "正在加载初始数据...";
                const [usersRes, modelsRes, recordsRes] = await Promise.all([
                    db.collection('users').get(),
                    db.collection('models').get(),
                    db.collection('records').orderBy('submitTime', 'desc').get()
                ]);

                allUsers = usersRes.data.map(doc => ({ _id: doc._id, ...doc }));
                allModels = modelsRes.data.map(doc => ({ _id: doc._id, ...doc }));
                allRecords = recordsRes.data.map(doc => ({ _id: doc._id, ...doc }));

                renderUsers();
                renderModels();
                populateDetailFilters();
                renderPendingRecords(allRecords.filter(r => r.status === 'pending'));
                if (document.getElementById('page-records').classList.contains('active')) {
                    applyAllFilters();
                }

                setupWatchers();
                loadingOverlay.classList.add('hidden');
            } catch (error) {
                console.error("Initialization Failed:", error);
                loadingText.innerHTML = `<p class="text-red-500 text-lg">加载失败: ${error.message}</p>`;
                const loader = loadingOverlay.querySelector('.loader');
                if(loader) loader.style.display = 'none';
            }
        }

        function setupWatchers() {
            const processSnapshot = (snapshot, targetArray, renderer, postAction) => {
                snapshot.docChanges.forEach(change => {
                    const changedDoc = { _id: change.docId, ...change.doc };
                    const index = targetArray.findIndex(item => item._id === change.docId);

                    if (change.dataType === 'add' || change.dataType === 'init') {
                        if (index === -1) targetArray.push(changedDoc);
                    } else if (change.dataType === 'update') {
                        if (index > -1) targetArray[index] = changedDoc;
                    } else if (change.dataType === 'remove') {
                        if (index > -1) targetArray.splice(index, 1);
                    }
                });
                if (targetArray === allRecords) {
                     targetArray.sort((a, b) => new Date(b.submitTime) - new Date(a.submitTime));
                }
                renderer();
                if (postAction) postAction();
            };

            db.collection('users').watch({
                onChange: (snapshot) => processSnapshot(snapshot, allUsers, renderUsers, populateDetailFilters),
                onError: (err) => console.error("Users watch error:", err)
            });

            db.collection('models').watch({
                onChange: (snapshot) => processSnapshot(snapshot, allModels, renderModels, populateDetailFilters),
                onError: (err) => console.error("Models watch error:", err)
            });

            db.collection('records').orderBy('submitTime', 'desc').watch({
                onChange: (snapshot) => {
                     processSnapshot(snapshot, allRecords, () => {
                        renderPendingRecords(allRecords.filter(r => r.status === 'pending'));
                        if (document.getElementById('page-records').classList.contains('active')) {
                            applyAllFilters();
                        }
                    });
                },
                onError: (err) => console.error("Records watch error:", err)
            });
        }
        
        main();
    };
    </script>
</body>
</html>
